import { useRef } from 'react'
import { connect } from 'dva'
import { nanoid } from 'nanoid'

const Female = (props: any) => {
  const nameInput = useRef<HTMLInputElement>(null)
  const ageInput = useRef<HTMLInputElement>(null)
  const getData = async () => {
    try {
      const res = await fetch('/api/tags')
      const data = await res.json()
      //在data.info中取到数据
      console.log(data.info);
    } catch (error) {
      console.log(error);
    }
  }
  const addPerson = () => {
    const name = nameInput.current?.value
    const age = ageInput.current?.value
    const id = nanoid()
    if (name !== '' && age !== '') {
      props.addFemale({ id, name, age });
      (nameInput.current as HTMLInputElement).value = '';
      (ageInput.current as HTMLInputElement).value = ''
    } else {
      alert('姓名和年龄不能为空')
    }
  }
  return (
    <>
      <h2>我是Female</h2>
      <button onClick={getData}>fetch请求mock数据</button>
      <br />
      <div>
        <span>姓名：</span>
        <input ref={nameInput} type="text" placeholder="请输入姓名" />
      </div>
      <div>
        <span>年龄：</span>
        <input ref={ageInput} type="text" placeholder="请输入年龄" />
      </div>
      <button onClick={addPerson}>添加女人</button>
      <ul>
        {
          props.femaleList.map((item: any) => {
            return <li key={item.id}>{item.name} : {item.age}</li>
          })
        }
      </ul>
    </>
  )
}

const actionCreator = {
  addFemale: (payload: any) => ({ type: 'store/addFemale', payload })
}

export default connect((state: any) => ({ femaleList: state.store.female }), actionCreator)(Female)
